import {
    apiPath,
    apiUrl
} from '@/config/index'
const getToken = () => {
    return wx.getStorageSync('token');
}
const HTTP = {
    request: (type = 'GET', {
        url,
        params,
        isToken = true,
        isToast = true,
        header = {}
    }) => {
        return new Promise((resolve, reject) => {
            if (isToken) {
                const token = getToken()
                if (!token) {
                    wx.navigateTo({
                        url: '/pages/login/login'
                    })
                    return;
                }
                header['Authorization'] = 'Bearer ' + token
            }
            wx.request({
                url: apiUrl + apiPath + url,
                method: type,
                header: header,
                data: params || {},
                success: ({
                    data
                }) => {
                    apiSuccess(data, resolve, reject, isToken, isToast)
                },
                fail: (err) => {
                    console.log(err)
                    wx.showToast({
                        title: '网络异常！',
                        icon: 'error',
                    })
                    reject(err)
                }
            })
        })
    }
}

const apiSuccess = (res, resolve, reject, isToken, isToast) => {
    if (res.code === 200) {
        resolve(res)
    } else if (res.code === 401) {
        if (isToken && !getToken()) {
            wx.showToast({
                title: '未登录',
                icon: 'error',
                complete: () => {
                    wx.navigateTo({
                        url: '/pages/login/login'
                    })
                }
            })
        }
    } else {
        isToast && wx.showToast({
            title: res.msg,
            icon: 'error',
        })
        reject(res)
    }
}

export default HTTP